package logic

import (
	"context"
	"errors"
	"manuscript-service/modles/mysql"

	"manuscript-service/servicerpc/internal/svc"
	"manuscript-service/servicerpc/servicerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ArticleAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewArticleAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ArticleAddLogic {
	return &ArticleAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ArticleAddLogic) ArticleAdd(in *servicerpc.ArticleAddRequest) (*servicerpc.ArticleAddResponse, error) {
	// todo: add your logic here and delete this line

	begin := mysql.DB.Begin()
	var FindTitle mysql.Article

	if err := FindTitle.ArticlesFindByTitle(begin, in.Title); err == nil {
		begin.Rollback()
		return nil, errors.New("稿件名称已存在")
	}

	var classes = mysql.Class{
		Name: in.ClassName,
	}
	if err := classes.ClassFindByName(begin, in.ClassName); err != nil {
		begin.Rollback()
		return nil, err
	}

	var articles = &mysql.Article{
		Title:   in.Title,
		Content: in.Content,
		Author:  in.Author,
		ClassId: int64(classes.ID),
	}

	err := articles.ArticlesAdd(begin)
	if err != nil {
		begin.Rollback()
		return nil, errors.New("稿件添加失败")
	}
	begin.Commit()
	return &servicerpc.ArticleAddResponse{
		ArticleId: int64(articles.ID),
	}, nil
}
